﻿using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class HallPanel : PanelBase
{

    public List<Toggle> playerList;
    public GameObject readyBtn;

    private void Awake()
    {
        EventManager.PlayerReady += PlayerReady;
        EventManager.loginSuccess += PlayerLogin;
        EventManager.OtherPlayers += OtherPlayerInfo;
        EventManager.PlayerLogout += PlayerLogout;
        EventManager.AllPlayerEnterGame += AllEnterGame;

    }
    private void OnDestroy()
    {
        EventManager.PlayerReady -= PlayerReady;
        EventManager.loginSuccess -= PlayerLogin;
        EventManager.OtherPlayers -= OtherPlayerInfo;
        EventManager.PlayerLogout -= PlayerLogout;
        EventManager.AllPlayerEnterGame -= AllEnterGame;
    }

    void Start () {

        readyBtn.GetComponent<Button>().onClick.AddListener(OnReadyClick);

        this.PlayerLogin(UIManager.Instance.localUserData,true);
    }
	
    //准备按钮点击
    public void OnReadyClick()
    {
        readyBtn.SetActive(false);

        string json = JsonUtility.ToJson(UIManager.Instance.localUserData);
        NetworkManager.Instance.SendMessage(Protocol.PlayerReady_CMD,json);
    }

	//玩家进入
    public void PlayerLogin(UserData user,bool islocal)
    {
        Text label = playerList[user.index].GetComponentInChildren<Text>();
        label.text = user.username;
    }

    //玩家准备
    public void PlayerReady(UserData user)
    {
        playerList[user.index].isOn = true;
    }

    //其他玩家列表
    public void OtherPlayerInfo(List<UserData> list)
    {
        foreach (var user in list)
        {
            Toggle toggle = playerList[user.index];
            Text label = toggle.GetComponentInChildren<Text>();
            label.text = user.username;
            toggle.isOn = user.isReady;
        }
    }

    //玩家退出游戏
    public void PlayerLogout(UserData user)
    {
        Toggle toggle = playerList[user.index];
        Text label = toggle.GetComponentInChildren<Text>();
        label.text ="等待玩家....";
        toggle.isOn = false;
    }

    void AllEnterGame(List<UserData> list)
    {
        Destroy(this.gameObject);
    }

    public override void InitData(params object[] options)
    {
        
    }
}
